<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/common/taglibs.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>sql列表</title>
	<%@ include file="/common/meta.jsp" %>
<script type="text/javascript">
var flagData = [];
var orderByData = [];
var _sqlQueryWhere = [];

$(function() {
	flagData = $.fn.module.getFlagData();
	orderByData = $.fn.module.getOrderByData();
	_sqlQueryWhere = $.fn.module.getSqlQueryWhere();
});

			function flagDataType(value){
	 			for(var i=0; i<flagData.length; i++){
	 				if (flagData[i].key == value) return flagData[i].caption;
	 			}
	 			return value;
	 		}

				function orderByDataType(value){
		 			for(var i=0; i<orderByData.length; i++){
		 				if (orderByData[i].key == value) return orderByData[i].caption;
		 			}
		 			return value;
		 		}
     		
    		 function sqlQueryType(value){
    			for(var i=0; i<_sqlQueryWhere.length; i++){
    				if (_sqlQueryWhere[i].key == value) return _sqlQueryWhere[i].caption;
    			}
    			return value;
    		};
    		
    		function doRefreshSqlList() {
    			var getSqlListFunc = parent.getSqlListData;
    			if(getSqlListFunc) {
    				var data = getSqlListFunc();
    				data = data || [];
    				var dgData = {"total":data.length,"rows":data};
    				$("#dgSqlList").datagrid("loadData", dgData);
    			} 
    		}
    		//保存sql语句
    		function doSaveSql() {
    			var enValue = $("#entityName").combobox("getValue");
    			var dsValue = $("#dataStatus").combobox("getValue");
    			var data = {
    				"key":$("#sqlKey").val(),
    				"caption":$("#sqlName").val(),
    				"content":$("#sqlContent").val(),
    				"sqlSelect":$("#sqlSelect").val(),
    				"entityName":enValue,
    				"dataStatus":dsValue
    			};
    			if($("#isCheckAuth").attr("checked")) {
    				if(!enValue) {
    					$.messager.alert('提示信息', "请选择来源模块表",'info');
    					return false;
    				}
    				data["isCheckAuth"] = true;
    			} else {
    				data["isCheckAuth"] = false;
    			}
    			data["isUseCache"] = ($("#isUseCache").attr("checked")?true:false);
    			$("#dgSqlEdit").edatagrid("saveRow");
    			var rows = $("#dgSqlEdit").edatagrid("getRows");
    			data["rows"] = rows;
	    		if(tableKeys.length){
	    			var selectInfo = {
	    				"tableItemList" : [],
	    				"whereItemList" :[]
	    			};    		
	    			var tableAry = [];
	    			for(var i=0;i<tableKeys.length;i++){	  			
	    				var itemProp={
	        					"key":"",
	        					"caption":"",
	        					"column":"",
	        					"order":"",
	        					"operator":"",
	        					"value":""
	        			}; 
	    				var tk = $("#"+tableKeys[i].table).combobox("getValue"); 
	    				var fields = $("#"+tableKeys[i].fields).find("option");					
	    				itemProp["key"]= tableKeys[i].table;//获取映射条件
	    				itemProp["caption"]=tk;
	    				itemProp["value"]=tableKeys[i].fields
	    				var columstr = [];
	    				for(var j=0;j<fields.length;j++){
	    					 if(fields[j].selected){
	    						 columstr.push(fields[j].text);
		    				}		    				    					
	    				}	    				
	    				itemProp["column"] = columstr.join(",");
	    				tableAry.push(itemProp);
	    			}
	    			selectInfo["tableItemList"] = tableAry;
	    			var whereRows = $("#sqlWhereTable").edatagrid("getRows");
	    			if(whereRows && whereRows.length && whereRows[0].column){
	    				var sqlWhereAry = [];				
							$.each(whereRows,function(k,v){
								var itemProp={
			        					"key":"",
			        					"caption":"",
			        					"column":"",
			        					"order":"",
			        					"operator":"",
			        					"value":""
			        			}; 
								if(v.flag=="sqlWhere"){	//获取查询条件														
									itemProp["key"] = v.flag;
									itemProp["caption"] = v.referColumn;
									itemProp["column"] = v.column;
									itemProp["operator"] =v.operator;
									itemProp["value"] =v.value;									
									itemProp["order"] ="";
									sqlWhereAry.push(itemProp);
								}else if(v.flag=="orderBy"){//获取排序条件
									itemProp["key"] = v.flag;
									itemProp["column"] = v.column;								
									itemProp["order"] =v.order;
									sqlWhereAry.push(itemProp);
								}
							});
							selectInfo["whereItemList"] = sqlWhereAry;
	    			}
	    			data["selectInfo"] = selectInfo;
    			}
    			if(parent.setSqlListData) {
    				parent.setSqlListData(data);
    			}
    			doRefreshSqlList();
    			$('#sqlSetWin').window('close');
    		}
    		
    		//删除公式SQL语句属性行
    		  function delSqlViewRow(){
    			  var rowIndex =$("#dgSqlEdit").data("rowIndex");
				  if(rowIndex >= 0) {
	    			  $("#dgSqlEdit").edatagrid('deleteRow',rowIndex);
	    			  $("#dgSqlEdit").edatagrid('options').editIndex = rowIndex - 1;
				  }
    		  }	
    		
    		function getSelectRow() {
    			var rows = $("#dgSqlList").edatagrid('getSelections');
    			if(rows.length == 1) {
    				return rows[0];
    			} else if(rows.length == 0) {
    				$.messager.alert('提示信息', "请选择1条记录进行操作",'info');
    				return false;
    			} else {
    				$.messager.alert('提示信息', "只能选择1条记录进行操作",'info');
    				return false;
    			}
    		}
    		var tableKeys = [];
    		function doInitAdd() {
    			//打开及回车时sql语句表格自动添加行
				$("#dgSqlEdit").edatagrid("loadData",{"total":0,"rows":[]});
				$("#dgSqlEdit").edatagrid('addRow', {"flag":"setValue","key":"", "caption":""});
				//$("#dgSqlEdit").edatagrid('addRow', {"flag":"setValue","key":"key", "caption":""});
				//$("#dgSqlEdit").edatagrid('addRow', {"flag":"setValue","key":"caption", "caption":""});
				$("#selectTables").html("");
				tableKeys = [];
				var str = '<div style="float:left;padding:5px;"><div style="text-align:center;">查询表1</div><div><input id="selTab_1"  style="width:150px;"></input></div><div><select  id="selFields_1" multiple="multiple" style="width :150px;height:250px"></select></div></div>';
				$("#selectTables").append(str);
				var t = {
						"table" : "selTab_1",
						"fields" : "selFields_1"
				}
				tableKeys.push(t);
				getAllModule("selTab_1","selFields_1");			
    		}
    		function addSelectTable(){//添加查询表
    			var lastSel = $("#selectTables").find("select:last");
    			var num = 1;
    			if(lastSel && lastSel.length) {
    				var lastId = lastSel.attr("id");
    				num = parseInt(lastId.split("_")[1])+1;
    			}
				var str = '<div style="float:left;padding:5px;"><div style="text-align:center;">查询表'+num+'</div><div><input id="selTab_'+num+'"  style="width:150px;"></input></div><div><select  id="selFields_'+num+'" multiple="multiple" style="width :150px;height:250px"></select></div></div>';
				$("#selectTables").append(str);
				var t = {
						"table" : "selTab_"+num,
						"fields" : "selFields_"+num
				}
				tableKeys.push(t);
				getAllModule("selTab_"+num,"selFields_"+num);	
    		}
    	    //获得单个帐套中所有的模块
    	    function getAllModule(tableId,selectId,tableKey){
    	    	var treeId = "${param.treeId}";
    	    	var urlType = "${param.title}";
    	    	var options = {
    					data : {
    						"treeId":treeId,
    						"urlType":urlType
    					},
    					url: "${ctx}/design/doXml/getTabName",
    					success:function(data) {
    						var dataJson =[];
    						var flag = 0;
    						$.each(data.msg,function(k,v){
    							if(flag==0){
    								dataJson.push({"key":k,"caption":v,"selected":true });
    							}else{
    								dataJson.push({"key":k,"caption":v});
    							}
    							flag++;
    						});
    						$("#"+tableId).combobox({  
    						    "data":dataJson,  
    						    "valueField":"key",  
    						    "textField":"caption" ,
    						     "onSelect":function(record){
    						    	getAllField(treeId,urlType,record.key,selectId);
    						    } 
    						});
    						if(tableKey){
    							$("#"+tableId).combobox("setValue",tableKey);
    						}
    					}
    			};
    			fnFormAjaxWithJson(options);
    	    }
    	  //获取对应表下的字段
    	 	function getAllField(treeId,urlType,formKey,flag,seleOpts){

    	 	  		 var options = {
    	 					data : {
    	 						"treeId":treeId,
    	 						"formKey":formKey
    	 					},
    	 					url: "${ctx}/design/doXml/getFileName",
    	 					success:function(data) {
    	 	    				
    	 						var dataStr ="";
    	 						if(seleOpts && seleOpts.length>0){
    	 							field_data.splice(0,field_data.length);
    	 						}
    	 						$.each(data.msg,function(k,v){
    	 							if(seleOpts && seleOpts.length>0){
    	 								var sel =false;
    	 								for(var g=0;g<seleOpts.length;g++){  	 									
    	    	 	    					 if(v == seleOpts[g]){
    	    	 	    							sel= true;
    	    	 	    						break;
    	    	 		    				}
    	    	 	    				}
    	 								if(sel){
    	 									dataStr +="<option selected ='true' value="+k+">"+v+"</option>";
    	 								}else{
    	 									dataStr +="<option value="+k+">"+v+"</option>";
    	 								}
    	 								var fd = formKey+"."+k;    	 								
    	 								field_data.push({"key":fd,"caption":fd});
    	 							}else{
    	 								dataStr +="<option value="+k+">"+v+"</option>";
    	 							}
    	 						});
    	 						
    	 						$("#"+flag).html(dataStr);
 
    	 					}
    	 				};    	 	  		
    	 	  		fnFormAjaxWithJson(options);   	 	
    	 	  	}
    	 	
    	 	  var field_data = [];
				function fieldType(value){
					for(var i=0;i<field_data.length;i++){
						if(field_data[i].key==value)return field_data[i].caption;
					}
					return value;
				}
				//获取初始化sql查询条件
    		function initSqlWhereGrid(){
    			field_data.splice(0,field_data.length); 
    			for(var i=0;i<tableKeys.length;i++){
    				var tk = $("#"+tableKeys[i].table).combobox("getValue");
    				var fields = $("#"+tableKeys[i].fields).find("option");
    				for(var j=0;j<fields.length;j++){
    					var k = tk+"."+$(fields[j]).val();    				
    					field_data.push({"key":k,"caption":k});
    				}
    			}
    			$("#sqlTabs").tabs("select",1);
        		$("#sqlWhereTable").edatagrid("addRow",{"flag":"sqlWhere"});
    		}
    		

		var flag_data = [	{key:'sqlWhere',caption:"查询条件"},
					{key:'orderBy',caption:"排序方式"}
				];
				function flagType(value){
		 			for(var i=0; i<flag_data.length; i++){
		 				if (flag_data[i].key == value) return flag_data[i].caption;
		 			}
		 			return value;
		 		}
		var orderBy_data = [{key:'ASC',caption:"升序"},
				     	{key:'DESC',caption:"降序"},
				     	{key:'',caption:"空值"}		     	
				    ];
					function orderByType(value){
			 			for(var i=0; i<orderBy_data.length; i++){
			 				if (orderBy_data[i].key == value) return orderBy_data[i].caption;
			 			}
			 			return value;
			 		}
					//根据查询表，字段，以及查询条件创建sql语句，
					function createSql(){
						var sqlStr = [];
						var nickName = ["a","b","c","d","e","f","g"];
						var form = [];
						var tnn = [];
						sqlStr.push("SELECT ");
						form.push(" FROM ")
						$("#dgSqlEdit").edatagrid('loadData',[]);
						for(var i=0;i<tableKeys.length;i++){						
		    				var tk = $("#"+tableKeys[i].table).combobox("getValue");
		    				var tn = nickName[i];
		    				var tableNick = {
		    						"key" : tk,
		    						"value" : tn
		    				}
		    				tnn.push(tableNick);
		    				form.push(tk+" "+tn+",");
		    				
		    				var fields = $("#"+tableKeys[i].fields).find("option");		    				
		    				for(var j=0;j<fields.length;j++){
		    					 if(fields[j].selected){
		    						 $("#dgSqlEdit").edatagrid('addRow', {"flag":"setValue","column":fields[j].value,"key":fields[j].value.toLowerCase(), "caption":fields[j].text});
			    						sqlStr.push(tn+"."+fields[j].value+",");
			    					}		    				    					
		    				}
		    			}
						var lastone = sqlStr[sqlStr.length-1];
						sqlStr.splice(sqlStr.length-1,1,lastone.split(",")[0]);
						var lastfone = form[form.length-1];
						form.splice(form.length-1,1,lastfone.split(",")[0]);
						var sql = sqlStr.join("")+form.join("");
						
						
						$("#sqlWhereTable").edatagrid("saveRow");
						var whereRows = $("#sqlWhereTable").edatagrid("getRows");
						if(whereRows && whereRows.length && whereRows[0].column){
							var sqlWhereStr = "";	
							var orderByStr = "";
							$.each(whereRows,function(k,v){
								if(v.flag=="sqlWhere"){		
									var key = v.column.split(".");
									var table = key[0];
									$.each(tnn,function(k,v){
										if(v.key==table){
											table = v.value;												
										}
									});								
									var field = table+"."+key[1];
									if(v.value){
										sqlWhereStr += " "+field+" "+v.operator+" "+v.value +" and";
									}else if(v.referColumn){
										var key2 = v.referColumn.split(".");
										var table2 = key2[0];
										$.each(tnn,function(k,v){
											if(v.key==table2){
												table2 = v.value;												
											}
										});								
										var referField = table2+"."+key2[1];
										sqlWhereStr += " "+field+" "+v.operator+" "+referField +" and";
									}
									
								}else if(v.flag=="orderBy"){
									var key = v.column.split(".");
									var table = key[0];
									$.each(tnn,function(k,v){
										if(v.key==table){
											table = v.value;												
										}
									});	
									var field = table+"."+key[1];
									orderByStr +=" "+ field + " "+v.order+",";
								}
							});
							var whereStr = sqlWhereStr.substring(0, sqlWhereStr.length-3);
							var orderStr = orderByStr.substring(0, orderByStr.length-1);
							if(whereStr.length>0){
								whereStr =" WHERE "+ whereStr;
							}							
							if(orderStr.length>0){
								orderStr = " ORDER BY "+orderStr;
							}
							sql = sql + whereStr + orderStr;
							$("#sqlTabs").tabs("select",3);
							$("#sqlSelect").val("");
							$("#sqlContent").val(sql);
						}else{														
							$("#sqlTabs").tabs("select",2);
							$("#sqlContent").val("");
							$("#sqlSelect").val(sql);
						}
					}
					
					//修改sql语句
    		function doInitEdit(row) {
    			var data = $.fn.module.convertSqlToData(row);
				$("#sqlName").val(data["caption"]);
			 	$("#sqlKey").val(data["key"]);
			 	$("#spanSqlKey").text(data["key"]);
			 	$("#sqlSelect").val(data["sqlSelect"]);
			 	$("#sqlContent").val(data["content"]);
			 	$("#entityName").combobox("setValue", data["entityName"]);
			 	$("#dataStatus").combobox("setValue", data["dataStatus"]);
			 	if(data["isCheckAuth"]) {
			 		$("#isCheckAuth").attr("checked", true);
			 		//$("#span_entityName").show();
			 	}
			 	if(data["isUseCache"]) {
			 		$("#isUseCache").attr("checked", true);
			 	}
			 	var dataRows = data["rows"];
				$("#dgSqlEdit").edatagrid("loadData",{"total":dataRows.length,"rows":dataRows});
				$("#dgSqlEdit").edatagrid('addRow', {"flag":"setValue","key":"", "caption":""});
							 
				var tableInfo = data["selectInfo"]?data["selectInfo"].tableItemList:[];
				$("#selectTables").html("");
				tableKeys = [];
				var treeId = "${param.treeId}";
    	    	var urlType = "${param.title}";
				for(var j=0;j<tableInfo.length;j++){					
					var str = '<div style="float:left;padding:5px;"><div style="text-align:center;">查询表'+(j+1)+'</div><div><input id="'+tableInfo[j].key+'"  style="width:150px;"></input></div><div><select  id="'+tableInfo[j].value+'" multiple="multiple" style="width :150px;height:250px"></select></div></div>';
					$("#selectTables").append(str);
					getAllModule(tableInfo[j].key,tableInfo[j].value,tableInfo[j].caption);
					var t = {
							"table" : tableInfo[j].key,
							"fields" : tableInfo[j].value
					};
					tableKeys.push(t);											
	    	    	var seleOpt = tableInfo[j].column.split(",");
					getAllField(treeId,urlType,tableInfo[j].caption,tableInfo[j].value,seleOpt);													 					
				}
				
				var whereInfo = data["selectInfo"]?data["selectInfo"].whereItemList:[];
				$("#sqlWhereTable").edatagrid({onRowContextMenu:function(e, rowIndex, rowData){
					 e.preventDefault(); 
					 $("#sqlWhereTable").edatagrid("selectRow",rowIndex);
						$('#delSqlWhere').menu('show',{
				    			left:e.pageX,
				    			top:e.pageY
				    	});  
				 }});							
				if(whereInfo && whereInfo.length>0){
					for(var k=0;k<whereInfo.length;k++){
						var row = {
								"flag": whereInfo[k].key,
								"column":whereInfo[k].column,
	        					"order":whereInfo[k].order,
	        					"operator":whereInfo[k].operator,
	        					"value":whereInfo[k].value							
						};
	        		$("#sqlWhereTable").edatagrid("addRow",row);	        		
					}					
				}
				$("#sqlWhereTable").edatagrid("addRow",{"flag":"sqlWhere"});
											
				if($("#sqlSelect").val()){
					$("#sqlTabs").tabs("select",2);
				}else if($("#sqlContent").val()){
					$("#sqlTabs").tabs("select",3);
				}
				
    		}
    		
    		function doSelectSelKey() {
    			if(parent.getCurrentSqlKey) {
					var selKey = parent.getCurrentSqlKey();
					if(selKey) {
						$("#dgSqlList").datagrid("selectRecord", selKey);
					}
				}
    		}
    		//获取所有模块表
    		function loadModuleTables() {
    			var options = {
    					data : {
    						"treeId":"${param.treeId}",
    						"urlType":"${param.title}"
    					},
    					url: "${ctx}/design/doXml/getModuleTables",
    					success:function(data) {
    						var tbData = data.msg;
    						if(tbData) {
    							$("#entityName").combobox({  
    							    "data":tbData,
    							    "valueField":"key",  
    							    "textField":"caption"
    							});
    						}
    					}
    				}; 
    	  		fnFormAjaxWithJson(options);
    		}
    		
    		function loadDataStatus() {
    			var dsData = $.fn.module.getDataStatus();
    			$("#dataStatus").combobox({  
				    "data":dsData,
				    "valueField":"key",  
				    "textField":"caption"
				});
    		}
    		
var entityName = "";    		
$(function() {
	entityName = parent.getEntityName();
	$("#dgSqlList").datagrid({
        rownumbers:true,
        singleSelect:true,
        idField:"key",
        frozenColumns:[[
		    {field:'ck',checkbox:true}
		]],
    	columns:[[  
    	          {field:'sqlKey',title:'引用key',width:400,
    	        	  formatter: function(value,row,index){
    					return entityName + "." + row["key"];
    				  }},
    	          {field:'key',title:'sqlKey',width:100},
    	          {field:'caption',title:'sql名称',width:100}
    	]],
    	toolbar:[{
				text:'新增Sql',
				iconCls:'icon-add',
				handler:function(){
					$("#sqlSetWin").data("row", null);
					$("#sqlSetWin").window("open");
	    			$("#sqlWhereTable").edatagrid({onRowContextMenu:function(e, rowIndex, rowData){
	    				 e.preventDefault(); 
	    				 $("#sqlWhereTable").edatagrid("selectRow",rowIndex);
	    					$('#delSqlWhere').menu('show',{
	    			    			left:e.pageX,
	    			    			top:e.pageY
	    			    	});  
	    			 }});
				}
		},'-',{
				text:'修改Sql',
				iconCls:'icon-edit',
				handler:function(){
					var row = getSelectRow();
					if(row) {
						$("#sqlSetWin").data("row", row);
						$("#sqlSetWin").window("open");
					}
		  		}
		},'-',{
				text:'删除Sql',
				iconCls:'icon-remove',
				handler:function(){
					var row = getSelectRow();
					if(row) {
						if(parent.delSql) {
							parent.delSql(row);
							doRefreshSqlList();
						}
					}
		  		}
		},'-',{
			text:'复制sql语句',
			handler:function(){
				var row = getSelectRow();
				if(row) {
					var getSqlListFunc = parent.getSqlListData;//获得读取当前字段sql集合的方法
	    			if(getSqlListFunc) {
	    				var currentData = getSqlListFunc();
	    				for(var i=0,len=currentData.length;i<len;i++){
	    					if(currentData[i]["key"]==row["key"]){
	    						if(parent.parent.copySqls){						
	    							parent.parent.copySqls(currentData[i]);
	    						 }
	    						break;
	    					}
	    				}
	    			}
					
				}else{
					alert("请选中一条sql语句");
				}
	  		}
		},'-',{
			text:'粘贴sql语句',
			handler:function(){
		 		if(parent.parent.getPasteSqls){
		 			var getPasteSqls = parent.parent.getPasteSqls;//获得读取复制的sql对象的方法
		 			var getSqlListFunc = parent.getSqlListData;//获得读取当前字段sql集合的方法
	    			if(getSqlListFunc && getPasteSqls) {
	    				var sqlData = getPasteSqls();
	    				var newsql = $.extend(true,{}, sqlData);
	    				var currentData = getSqlListFunc();
	    				currentData = currentData || [];
	    				var len = currentData.length;
	    				var orderNo = "0";
	    				if(len > 0) orderNo = currentData[len-1]["key"];
	    				orderNo = orderNo.replace("sql","");
						orderNo = parseInt(orderNo)+1;
						newsql["key"]="sql"+orderNo;	    						    			
	    				if(parent.addSqlListData) {
	        				parent.addSqlListData(newsql);
	        			}
	    				doRefreshSqlList();
	    			} 
				} 
	  		}
		}]
    });
	
	doRefreshSqlList();
	doSelectSelKey();
	
	$("#dgSqlEdit").edatagrid({onRowContextMenu:function(e, rowIndex, rowData){
		e.preventDefault(); 
		$("#dgSqlEdit").edatagrid("selectRow",rowIndex);
		$('#delSql').menu('show',{
    			left:e.pageX,
    			top:e.pageY
    	});  
		$("#dgSqlEdit").data("rowIndex",rowIndex);
	}});
	
	$('#sqlSetWin').window({
		maximized :true,
		onOpen:function() {
			$(this).window("move", {
				top:($(window).height()-450)*0.5,
				left:($(window).width()-680)*0.5
			});
			var row = $("#sqlSetWin").data("row");
			if(row) {
				doInitEdit(row);
			} else {
				doInitAdd();
			}
		},onClose:function() {
			$("#sqlName").val("");
		 	$("#sqlKey").val("");
		 	$("#sqlSelect").val("");
		 	$("#sqlContent").val("");
		 	$("#isCheckAuth").removeAttr("checked");
		 	$("#isUseCache").removeAttr("checked");
		 	$("#entityName").val("");
		 	loadDataStatus();
		 	//$("#span_entityName").hide();
		 	$("#spanSqlKey").text("(自动)");
		 	$("#dgSqlEdit").edatagrid("cancelRow");
		}
	});
	
	loadModuleTables();
	loadDataStatus();
	
	/*$("#isCheckAuth").click(function() {
		var val = $(this).attr("checked");
		if(val) {
			$("#span_entityName").show();
		} else {
			$("#span_entityName").hide();
		}
	});*/
	
	$("#sqlView input").live('keydown', 'return',function (evt){$("#dgSqlEdit").edatagrid('addRow',{"flag":"setValue","order":""});});
	$("#sqlWhere input").live('keydown', 'return',function (evt){$("#sqlWhereTable").edatagrid("addRow",{"flag":"sqlWhere"}); return false; });
});
function delSqlWhereRow(){
	var rowData = $("#sqlWhereTable").edatagrid("getSelected");
	var index = $("#sqlWhereTable").edatagrid("getRowIndex",rowData);
	$("#sqlWhereTable").edatagrid("deleteRow",index);
}
//上移
function moveUp() {
	var rowIndex = parseInt($('#dgSqlEdit').data('rowIndex'));
	if (rowIndex > 0) {
		var rows = $("#dgSqlEdit").edatagrid("getRows");
		var currentRow = $.extend(true,{}, rows[rowIndex]);
		var lastRow = $.extend(true,{}, rows[rowIndex - 1]);
		$('#dgSqlEdit').edatagrid('updateRow', {
			index : rowIndex - 1,
			row : currentRow
		});
		$('#dgSqlEdit').edatagrid('updateRow', {
			index : rowIndex,
			row : lastRow
		});
	}
	$('#dgSqlEdit').edatagrid('unselectRow', parseInt(rowIndex));
	$('#dgSqlEdit').edatagrid('selectRow', parseInt(rowIndex - 1));
}
//下移
function moveDown() {
	var rowIndex = parseInt($('#dgSqlEdit').data('rowIndex'));
	var rows = $("#dgSqlEdit").edatagrid("getRows");
	if (rowIndex < rows.length - 1) {
		var currentRow = $.extend(true,{}, rows[rowIndex]);
		var nextRow = $.extend(true,{}, rows[rowIndex + 1]);
		$('#dgSqlEdit').edatagrid('updateRow', {
			index : rowIndex + 1,
			row : currentRow
		});
		$('#dgSqlEdit').edatagrid('updateRow', {
			index : rowIndex,
			row : nextRow
		});
	}
	$('#dgSqlEdit').datagrid('unselectRow', parseInt(rowIndex));
	$('#dgSqlEdit').datagrid('selectRow', parseInt(rowIndex + 1));
}

//根据自定义sql语句生成规则
function genParamRuleBySql() {
	var sql = $("#sqlContent").val();
	if(sql) {
		var lsql = sql.replace(/\n/g, " ").toLowerCase();
		var startIndex = lsql.indexOf("select ");
		var endIndex = lsql.indexOf(" from");
		if(startIndex >= 0 && endIndex >= 0) {
			var str = sql.slice(startIndex+7, endIndex);
			if(str) {
				var arr = str.split(",");
				if(arr && arr.length) {
					var attrArr = $.map(arr, function(n) {
						//判断空格与AS两种情况
						var tmpArr = $.trim(n).split(/\s+/);
						var fieldName = tmpArr[tmpArr.length-1];
						//判断是否存在别名
						if(fieldName.indexOf(".") >=0) {
							fieldName = fieldName.slice(fieldName.indexOf(".")+1);
						}
						return fieldName;
					});
					$("#dgSqlEdit").edatagrid("loadData", []);
					//加入数据
					for(var i in attrArr) {
						var a = attrArr[i];
						var la = a.toLowerCase();
						var row = {"flag":"setValue","column":a,"key":la, "caption":la};
						$("#dgSqlEdit").edatagrid('addRow', row);
					}
				}
			}
		}
	}
}
</script>
</head>
<body  class="easyui-layout" fit="true">
	<div region="center" style="padding:0px;" fit="true">
		<table id="dgSqlList" fit="true"></table>
	</div>
	<div id="sqlSetWin" class="easyui-window" title="数据源设置" closed="true" modal="true" minimizable="false" maximizable="true" collapsible="false" closable="true" style="width:700px;height:450px;padding:0px;">
				<div class="easyui-layout" fit="true" >
				 	<div region="center" border="false" style="width:100%;height:100%;padding:0px;background:#fff;border:1px solid #ccc;" >
				 		<div>
				 			<table border="0" cellpadding="0" cellspacing="1" class="table_form">
								<tr>
									<th style="width:60px;"><label for="sqlName">sql名称:</label></th>
									<td><input style="width:200px;" id="sqlName" name="sqlName" type="text"/>
										&nbsp;&nbsp;<label for="isUseCache">启用缓存:</label><input id="isUseCache" name="isUseCache" type="checkbox" value="1"/>启用
									</td>
									<th style="width:60px;"><label for="">sqlKey:</label></th>
									<td><input id="sqlKey" name="sqlKey" type="hidden" value=""/><span id="spanSqlKey" style="color:red;">(自动)</span></td>
								</tr>	
								<tr>
									<th style="width:60px;"><label>数据权限:</label></th>
									<td><input id="isCheckAuth" name="isCheckAuth" type="checkbox" value="1"/><label for="isCheckAuth">过滤</label>
									&nbsp;<span id="span_entityName"><label for="entityName">来源模块表:</label><input style="width:200px;" id="entityName"/></span>
									</td>
									<th style="width:60px;"><label>数据状态:</label></th>
									<td><input style="width:160px;" id="dataStatus"/>
									</td>
								</tr>
							</table>
				 		</div>
						<div id="sqlTabs" class="easyui-tabs" >
							<div title="设置查询表">
		
								<div  id="selectTables" style="float:left;padding:5px;">
																	
								</div>
								
								<div   style="float:right;padding:5px;">
								<input type="button" value="添加查询表" onclick="addSelectTable()"/>
								<input type="button" value="下一步" onclick="initSqlWhereGrid()"/>
								</div>
							<!-- 	<div style="clear:both;"></div>					 -->
							</div>
							<div id ="sqlWhere" style="height:80%" title="设置查询条件">
								<table id="sqlWhereTable"  fit="true" rownumbers="true" singleSelect="true" style="width:100%;height:100%">
							 <thead>
								<tr>
									<th field="flag" width="90" formatter="flagType" editor="{type:'combobox',options:{valueField:'key',textField:'caption',data:flag_data}}">节点类型</th> 
									<th field="column" width="280" formatter="fieldType" editor="{type:'combobox',options:{valueField:'key',textField:'caption',data:field_data}}">字段名(column)</th>
									<th field="operator" width="95" formatter="sqlQueryType" editor="{type:'combobox',options:{valueField:'key',textField:'caption',data:_sqlQueryWhere}}">运算条件(operator)</th>
									<th field="value" width="80" editor="{type:'validatebox'}">值</th>
									<th field="referColumn" width="280" formatter="fieldType" editor="{type:'combobox',options:{valueField:'key',textField:'caption',data:field_data}}">关联字段</th>
									<th field="order" width="90" formatter="orderByType" editor="{type:'combobox',options:{valueField:'key',textField:'caption',data:orderBy_data}}">排序方式(order)</th> 
								</tr>
							</thead>  
							</table>
						    <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'"   onclick="javascript:createSql()">生成sql语句</a>  
								
							</div>
							<div title="sql生成规则">
						 		<table border="0" cellpadding="0" cellspacing="1" class="table_form">
											<tr>
												<th style="width:70px;"><label for="sqlSelect">查询语句:</label></th>
												<td><textarea name="sqlSelect" id="sqlSelect" style="width:98%;height:50px;"></textarea></td>
											</tr>	
								</table>
								<div id="sqlView">
									<table id="dgSqlEdit" rownumbers="true">
										<thead>
											<tr>
												<th field="flag" width="80" formatter="flagDataType" editor="{type:'combobox',options:{valueField:'key',textField:'caption',data:flagData}}">节点类型</th> 
												<th field="column" width="100" editor="{type:'validatebox'}">字段名(column)</th>
												<th field="operator" width="70" formatter="sqlQueryType" editor="{type:'combobox',options:{valueField:'key',textField:'caption',data:_sqlQueryWhere}}">运算符</th>
												<th field="value" width="90" editor="{type:'text'}">固定值</th>
												<th field="key" width="100" editor="{type:'validatebox'}">字段Key</th>
												<th field="caption" width="100" editor="{type:'validatebox'}">显示名称</th>
												<th field="order" width="70" formatter="orderByDataType" editor="{type:'combobox',options:{valueField:'key',textField:'caption',data:orderByData}}">排序/显隐</th>
												<th field="width" width="100" editor="{type:'text'}">列宽(width)</th>
												<th field="columntype" width="100" editor="{type:'combobox',options:{valueField:'key',textField:'caption',data:[{key:'string',caption:'字符串'},{key:'long',caption:'整型'}]}}">key字段类型</th>
											</tr>
										</thead>						
									</table>
								</div>
							</div>
							<div title="自定义sql语句">
								<table border="0" cellpadding="0" cellspacing="1" class="table_form">
											<tr>
												<th style="width:70px;"><label for="sqlContent">sql语句:</label></th>
												<td><textarea name="sqlContent" id="sqlContent" style="width:98%;height:250px;"></textarea>
													<a class="easyui-linkbutton"  href="javascript:void(0)" onclick="genParamRuleBySql();">根据自定义sql语句提取sql生成规则</a>
												</td>
											</tr>	
								</table>
							</div>
							<div title="设置前请先看注意事项" style="padding:10px;">
									<span style="color:red;">
									&nbsp;&nbsp;&nbsp;&nbsp;1、“运算符”和“固定值”仅在节点类型为“查询条件”时有效，“固定值”表示查询条件中的值是固定的，如："admin"、123或固定字段名等；<br/>
									&nbsp;&nbsp;&nbsp;&nbsp;2、“显示名称”和“显隐”仅在节点类型为“设置参数”时有效，此时“显隐”用于设置该字段是否隐藏，“排序”仅在节点类型为“排序方式”时有效；<br/>
									&nbsp;&nbsp;&nbsp;&nbsp;3、“字段Key”在节点类型为“设置参数”时，表示将数据库字段映射为页面显示key；在节点类型为“查询条件”时，表示查询条件中的值是动态的，由页面字段key对应的属性值决定；<br/>
									&nbsp;&nbsp;&nbsp;&nbsp;4、如果是复杂的sql语句，请使用“自定义sql语句”将完整的sql语句写好，然后在“sql生成规则”中将“设置参数”映射规则定义好；<br/>
									&nbsp;&nbsp;&nbsp;&nbsp;5、若为展示树形结构的查询语句时，节点类型为“设置参数”时，“字段Key”必须由[id,text,pid]组成；其他情况下“字段Key”由[key,caption]组成；<br/>
									&nbsp;&nbsp;&nbsp;&nbsp;6、设置查询表时，选择多个字段时，通过CTRL+鼠标左键进行多选。
									</span>
							</div>
						</div>
					</div>
					<div region="south" border="false" style="text-align:right;padding:2px 0;">
						<a class="easyui-linkbutton"  href="javascript:void(0)" onclick="doSaveSql();">保存</a>
						<a class="easyui-linkbutton"  href="javascript:void(0)" onclick="$('#sqlSetWin').window('close');">关闭</a>
					</div>
			</div>
   </div> 
   <!-- 删除公式sql属性   -->
			<div id="delSql" class="easyui-menu" style="width:100px;">
				<div iconCls="icon-remove" onclick="delSqlViewRow();">删除</div>
				<div onclick="moveUp();">上移</div>
				<div onclick="moveDown();">下移</div>
			</div>
	 <!-- 删除查询条件 -->
			<div id="delSqlWhere" class="easyui-menu" style="width:100px;">
				<div iconCls="icon-remove" onclick="delSqlWhereRow();">删除</div>
			</div>
</body>
</html>